import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QTableWidgetItem, 
                             QVBoxLayout, QHBoxLayout, QPushButton, 
                             QLineEdit, QLabel, QMessageBox, QFileDialog,
                             QDialog, QFormLayout, QComboBox, QDateEdit,
                             QApplication, QMenu, QAction, QHeaderView)
from PyQt5.QtCore import Qt, QDate, QTimer
from PyQt5.QtGui import QFont, QColor
import openpyxl
import re
from datetime import datetime
from database import Database
import os
import traceback

class AddEmployeeDialog(QDialog):
    """新增员工对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("新增员工")
        self.setModal(True)
        self.setFixedSize(500, 600)
        self.db = Database()
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 标题
        title_label = QLabel("新增员工信息")
        title_label.setFont(QFont("Arial", 12, QFont.Bold))
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 姓名
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入姓名")
        form_layout.addRow("姓名*:", self.name_input)
        
        # 性别
        self.gender_combo = QComboBox()
        self.gender_combo.addItems(["男", "女"])
        form_layout.addRow("性别:", self.gender_combo)
        
        # 身份证号
        self.id_card_input = QLineEdit()
        self.id_card_input.setPlaceholderText("18位身份证号码（最后一位可能是X）")
        self.id_card_input.textChanged.connect(self.validate_id_card)
        form_layout.addRow("身份证号*:", self.id_card_input)
        
        # 出生日期
        self.birth_date_edit = QDateEdit()
        self.birth_date_edit.setDate(QDate(1990, 1, 1))
        self.birth_date_edit.setCalendarPopup(True)
        form_layout.addRow("出生日期:", self.birth_date_edit)
        
        # 民族
        self.nation_input = QLineEdit()
        self.nation_input.setText("汉族")
        form_layout.addRow("民族:", self.nation_input)
        
        # 政治面貌
        self.political_combo = QComboBox()
        self.political_combo.addItems(["群众", "共青团员", "中共党员", "民主党派", "其他"])
        form_layout.addRow("政治面貌:", self.political_combo)
        
        # 联系方式
        self.phone_input = QLineEdit()
        self.phone_input.setPlaceholderText("请输入手机号码")
        form_layout.addRow("联系方式*:", self.phone_input)
        
        # 学校
        self.school_input = QLineEdit()
        self.school_input.setPlaceholderText("请输入学校名称")
        form_layout.addRow("学校:", self.school_input)
        
        # 部门
        self.department_input = QLineEdit()
        self.department_input.setPlaceholderText("请输入部门名称")
        form_layout.addRow("部门:", self.department_input)
        
        # 岗位
        self.position_input = QLineEdit()
        self.position_input.setPlaceholderText("请输入岗位名称")
        form_layout.addRow("岗位:", self.position_input)
        
        # 职称
        self.job_title_input = QLineEdit()
        self.job_title_input.setPlaceholderText("请输入职称")
        form_layout.addRow("职称:", self.job_title_input)
        
        # 入职日期
        self.hire_date_edit = QDateEdit()
        self.hire_date_edit.setDate(QDate.currentDate())
        self.hire_date_edit.setCalendarPopup(True)
        form_layout.addRow("入职日期*:", self.hire_date_edit)
        
        layout.addLayout(form_layout)
        
        # 状态标签
        self.status_label = QLabel("")
        self.status_label.setStyleSheet("color: red;")
        layout.addWidget(self.status_label)
        
       # 按钮布局
        button_layout = QHBoxLayout()
        
        submit_btn = QPushButton("提交")
        submit_btn.clicked.connect(self.submit_employee)
        button_layout.addWidget(submit_btn)
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def validate_id_card(self):
        """实时验证身份证号（支持最后一位为X）"""
        id_card = self.id_card_input.text().strip().upper()  # 转换为大写
        if len(id_card) > 0:
            # 更宽松的验证：允许空格和分隔符
            cleaned_id = re.sub(r'[-\s]', '', id_card)  # 移除空格和连字符
            
            # 验证身份证号格式：17位数字 + 1位数字或X
            pattern = r'^\d{17}[\dX]$'
            if re.match(pattern, cleaned_id):
                if len(cleaned_id) == 18:
                    # 自动格式化显示
                    if id_card != cleaned_id:
                        self.id_card_input.setText(cleaned_id)
                    self.status_label.setText("身份证号格式正确")
                    self.status_label.setStyleSheet("color: green;")
                else:
                    self.status_label.setText("")
            else:
                self.status_label.setText("身份证号格式错误（前17位数字，最后一位数字或X）")
                self.status_label.setStyleSheet("color: red;")
        else:
            self.status_label.setText("")
    
    def validate_input(self):
        """验证输入数据"""
        errors = []
        
        if not self.name_input.text().strip():
            errors.append("姓名不能为空")
        
        id_card = self.id_card_input.text().strip().upper()
        if not id_card:
            errors.append("身份证号不能为空")
        elif len(id_card) != 18:
            errors.append("身份证号必须是18位")
        else:
            # 验证身份证号格式
            pattern = r'^\d{17}[\dX]$'
            if not re.match(pattern, id_card):
                errors.append("身份证号格式错误（前17位数字，最后一位数字或X）")
        
        if not self.phone_input.text().strip():
            errors.append("联系方式不能为空")
        
        if errors:
            QMessageBox.warning(self, "输入错误", "\n".join(errors))
            return False
        
        return True
    
    def submit_employee(self):
        """提交员工信息"""
        try:
            if not self.validate_input():
                return
            
            employee_data = (
                self.name_input.text().strip(),
                self.gender_combo.currentText(),
                self.id_card_input.text().strip().upper(),  # 转换为大写存储
                self.birth_date_edit.date().toString("yyyy-MM-dd"),
                self.nation_input.text().strip(),
                self.political_combo.currentText(),
                self.phone_input.text().strip(),
                self.school_input.text().strip(),
                self.department_input.text().strip(),
                self.position_input.text().strip(),
                self.job_title_input.text().strip(),
                self.hire_date_edit.date().toString("yyyy-MM-dd")
            )
            
            success = self.db.add_employee(employee_data)
            
            if success:
                QMessageBox.information(self, "成功", "员工添加成功！")
                self.accept()
            else:
                QMessageBox.warning(self, "警告", "员工添加失败，可能身份证号已存在！")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"添加员工时发生异常：{str(e)}")

class EmployeeManager(QWidget):
    def __init__(self):
        super().__init__()
        self.db = Database()
        self.init_ui()
        QTimer.singleShot(100, self.load_data)
    
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 搜索区域
        search_layout = QHBoxLayout()
        
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入姓名、部门、岗位或身份证号搜索...")
        self.search_input.textChanged.connect(self.search_employees)
        search_layout.addWidget(self.search_input)
        
        import_btn = QPushButton("导入Excel")
        import_btn.clicked.connect(self.import_excel)
        search_layout.addWidget(import_btn)
        
        export_btn = QPushButton("导出Excel")
        export_btn.clicked.connect(self.export_excel)
        search_layout.addWidget(export_btn)
        
        add_btn = QPushButton("新增员工")
        add_btn.clicked.connect(self.show_add_employee_dialog)
        search_layout.addWidget(add_btn)
        
        # 添加批量删除按钮
        self.batch_delete_btn = QPushButton("批量删除")
        self.batch_delete_btn.clicked.connect(self.batch_delete_employees)
        self.batch_delete_btn.setEnabled(False)
        self.batch_delete_btn.setStyleSheet("QPushButton { background-color: #ff6b6b; color: white; }")
        search_layout.addWidget(self.batch_delete_btn)
        
        refresh_btn = QPushButton("刷新")
        refresh_btn.clicked.connect(self.load_data)
        search_layout.addWidget(refresh_btn)
        
        layout.addLayout(search_layout)
        
        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(15)  # 增加选择列
        headers = ["选择", "序号", "姓名", "性别", "身份证号", "出生日期", "民族", 
                  "政治面貌", "联系方式", "学校", "部门", "岗位", "职称", "入职日期", "操作"]
        self.table.setHorizontalHeaderLabels(headers)
        self.table.setAlternatingRowColors(True)
        self.table.setStyleSheet("""
            QTableWidget {
                gridline-color: #d0d0d0;
                font-size: 10pt;
            }
            QTableWidget::item:selected {
                background-color: #b0d0ff;
            }
        """)
        
        # 设置列宽
        self.table.setColumnWidth(0, 50)   # 选择列
        self.table.setColumnWidth(1, 50)   # 序号
        self.table.setColumnWidth(2, 80)   # 姓名
        self.table.setColumnWidth(3, 50)   # 性别
        self.table.setColumnWidth(4, 160)  # 身份证号
        self.table.setColumnWidth(5, 100)  # 出生日期
        self.table.setColumnWidth(6, 60)   # 民族
        self.table.setColumnWidth(7, 80)   # 政治面貌
        self.table.setColumnWidth(8, 100)  # 联系方式
        self.table.setColumnWidth(9, 100)  # 学校
        self.table.setColumnWidth(10, 100) # 部门
        self.table.setColumnWidth(11, 100) # 岗位
        self.table.setColumnWidth(12, 80)  # 职称
        self.table.setColumnWidth(13, 100) # 入职日期
        self.table.setColumnWidth(14, 80)  # 操作
        
        # 设置单选模式，使用复选框选择
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setSelectionMode(QTableWidget.SingleSelection)
        
        # 连接复选框变化信号
        self.table.cellChanged.connect(self.on_cell_changed)
        
        # 启用右键菜单
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.show_context_menu)
        
        layout.addWidget(self.table)
        self.setLayout(layout)
    
    def on_cell_changed(self, row, column):
        """复选框状态变化时更新批量删除按钮"""
        if column == 0:  # 只处理选择列的变化
            self.update_batch_delete_button()
    
    def update_batch_delete_button(self):
        """更新批量删除按钮状态"""
        selected_count = self.get_selected_count()
        self.batch_delete_btn.setEnabled(selected_count > 0)
        self.batch_delete_btn.setText(f"批量删除 ({selected_count})")
    
    def get_selected_count(self):
        """获取选中的记录数量"""
        count = 0
        for row in range(self.table.rowCount()):
            checkbox_item = self.table.item(row, 0)
            if checkbox_item and checkbox_item.checkState() == Qt.Checked:
                count += 1
        return count
    
    def get_selected_employee_ids(self):
        """获取选中的员工ID列表"""
        employee_ids = []
        employees = self.db.get_all_employees()
        
        for row in range(self.table.rowCount()):
            checkbox_item = self.table.item(row, 0)
            if checkbox_item and checkbox_item.checkState() == Qt.Checked:
                if row < len(employees):
                    employee_ids.append(employees[row][0])
        
        return employee_ids
    
    def batch_delete_employees(self):
        """批量删除员工"""
        try:
            employee_ids = self.get_selected_employee_ids()
            
            if not employee_ids:
                QMessageBox.warning(self, "警告", "请先选择要删除的员工！")
                return
            
            # 获取员工姓名用于显示
            employee_names = []
            employees = self.db.get_all_employees()
            for emp in employees:
                if emp[0] in employee_ids:
                    employee_names.append(emp[1])
            
            # 确认对话框
            reply = QMessageBox.question(
                self, "确认批量删除",
                f"确定要删除选中的 {len(employee_ids)} 名员工吗？\n"
                f"包括：{', '.join(employee_names[:3])}{'...' if len(employee_names) > 3 else ''}\n"
                "此操作不可恢复！",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                success = self.db.batch_delete_employees(employee_ids)
                if success:
                    QMessageBox.information(self, "成功", f"成功删除 {len(employee_ids)} 名员工")
                    self.load_data()
                else:
                    QMessageBox.critical(self, "错误", "批量删除员工失败")
                    
        except Exception as e:
            QMessageBox.critical(self, "错误", f"批量删除失败：{str(e)}")
    
    def show_context_menu(self, position):
        """显示右键菜单"""
        row = self.table.rowAt(position.y())
        if row >= 0:
            menu = QMenu()
            
            # 获取选中行的员工ID和姓名
            employee_name = self.table.item(row, 2).text()
            
            # 需要从数据库查询实际的员工ID
            employees = self.db.get_all_employees()
            if row < len(employees):
                employee_id = employees[row][0]  # 获取实际的数据库ID
                
                # 删除操作
                delete_action = QAction(f"删除 {employee_name}", self)
                delete_action.triggered.connect(lambda: self.delete_employee(employee_id, employee_name))
                menu.addAction(delete_action)
                
                # 查看请假记录
                view_leaves_action = QAction(f"查看 {employee_name} 的请假记录", self)
                view_leaves_action.triggered.connect(lambda: self.view_employee_leaves(employee_id, employee_name))
                menu.addAction(view_leaves_action)
                
                menu.exec_(self.table.viewport().mapToGlobal(position))
    
    def delete_employee(self, employee_id, employee_name):
        """删除员工"""
        reply = QMessageBox.question(
            self, "确认删除",
            f"确定要删除员工 {employee_name} 吗？\n此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            success = self.db.delete_employee(employee_id)
            if success:
                QMessageBox.information(self, "成功", f"员工 {employee_name} 已删除")
                self.load_data()
            else:
                QMessageBox.critical(self, "错误", "删除员工失败")
    
    def view_employee_leaves(self, employee_id, employee_name):
        """查看员工请假记录"""
        leaves = self.db.get_leaves_by_employee(employee_id)
        
        if not leaves:
            QMessageBox.information(self, "请假记录", f"员工 {employee_name} 暂无请假记录")
            return
        
        message = f"员工 {employee_name} 的请假记录:\n\n"
        for leave in leaves:
            message += f"类型: {leave[4]}, 时间: {leave[5]} 至 {leave[6]}, 天数: {leave[7]}, 状态: {leave[9]}\n"
            message += f"原因: {leave[8]}\n\n"
        
        QMessageBox.information(self, "请假记录", message)
    
    def show_add_employee_dialog(self):
        """显示新增员工对话框"""
        try:
            dialog = AddEmployeeDialog(self)
            if dialog.exec_() == QDialog.Accepted:
                QTimer.singleShot(100, self.load_data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"打开对话框失败：{str(e)}")
    
    def load_data(self):
        """加载员工数据"""
        try:
            employees = self.db.get_all_employees()
            
            # 断开信号连接，避免触发多次
            self.table.cellChanged.disconnect(self.on_cell_changed)
            
            self.table.setRowCount(len(employees))
            for row, emp in enumerate(employees):
                # 选择列 - 复选框
                checkbox_item = QTableWidgetItem()
                checkbox_item.setCheckState(Qt.Unchecked)
                checkbox_item.setTextAlignment(Qt.AlignCenter)
                checkbox_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                self.table.setItem(row, 0, checkbox_item)
                
                # 序号列
                seq_item = QTableWidgetItem(str(row + 1))
                seq_item.setTextAlignment(Qt.AlignCenter)
                seq_item.setBackground(QColor(240, 240, 240))
                seq_item.setFont(QFont("Arial", 9, QFont.Bold))
                # 设置不可编辑
                seq_item.setFlags(seq_item.flags() & ~Qt.ItemIsEditable)
                self.table.setItem(row, 1, seq_item)
                
                # 其他数据列
                for col in range(2, min(len(emp), 14)):
                    value = str(emp[col-1]) if emp[col-1] is not None else ""
                    item = QTableWidgetItem(value)
                    item.setTextAlignment(Qt.AlignCenter)
                    # 设置不可编辑
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    self.table.setItem(row, col, item)
                
                # 操作列（删除按钮）
                delete_btn = QPushButton("删除")
                delete_btn.clicked.connect(lambda checked, id=emp[0], name=emp[1]: 
                                         self.delete_employee(id, name))
                self.table.setCellWidget(row, 14, delete_btn)
            
            # 重新连接信号
            self.table.cellChanged.connect(self.on_cell_changed)
            
            self.table.setToolTip(f"共 {len(employees)} 条记录")
            self.update_batch_delete_button()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载数据失败：{str(e)}")
    
    def search_employees(self):
        """搜索员工"""
        try:
            search_text = self.search_input.text().strip()
            if not search_text:
                self.load_data()
                return
            
            employees = self.db.search_employees(search_text)
            
            # 断开信号连接
            self.table.cellChanged.disconnect(self.on_cell_changed)
            
            self.table.setRowCount(len(employees))
            for row, emp in enumerate(employees):
                # 选择列 - 复选框
                checkbox_item = QTableWidgetItem()
                checkbox_item.setCheckState(Qt.Unchecked)
                checkbox_item.setTextAlignment(Qt.AlignCenter)
                checkbox_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                self.table.setItem(row, 0, checkbox_item)
                
                # 序号列
                seq_item = QTableWidgetItem(str(row + 1))
                seq_item.setTextAlignment(Qt.AlignCenter)
                seq_item.setBackground(QColor(240, 240, 240))
                seq_item.setFont(QFont("Arial", 9, QFont.Bold))
                seq_item.setFlags(seq_item.flags() & ~Qt.ItemIsEditable)
                self.table.setItem(row, 1, seq_item)
                
                # 其他数据列
                for col in range(2, min(len(emp), 14)):
                    value = str(emp[col-1]) if emp[col-1] is not None else ""
                    item = QTableWidgetItem(value)
                    item.setTextAlignment(Qt.AlignCenter)
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    self.table.setItem(row, col, item)
                
                # 操作列（删除按钮）
                delete_btn = QPushButton("删除")
                delete_btn.clicked.connect(lambda checked, id=emp[0], name=emp[1]: 
                                         self.delete_employee(id, name))
                self.table.setCellWidget(row, 14, delete_btn)
            
            # 重新连接信号
            self.table.cellChanged.connect(self.on_cell_changed)
            
            self.table.setToolTip(f"找到 {len(employees)} 条匹配记录")
            self.update_batch_delete_button()
                    
        except Exception as e:
            QMessageBox.critical(self, "错误", f"搜索失败：{str(e)}")
    
    def parse_date_string(self, date_str):
        """解析各种格式的日期字符串"""
        if date_str is None:
            return ""
            
        date_str = str(date_str).strip()
        
        # 处理datetime对象
        if isinstance(date_str, datetime):
            return date_str.strftime("%Y-%m-%d")
        
        # 移除可能的中文描述
        date_str = date_str.replace('日期', '').replace('时间', '').strip()
        
        # 尝试解析常见日期格式
        patterns = [
            # yyyy/mm/dd 或 yyyy-mm-dd
            r'(\d{4})[/-](\d{1,2})[/-](\d{1,2})',
            # yyyy年mm月dd日
            r'(\d{4})年(\d{1,2})月(\d{1,2})日',
            # mm/dd/yyyy 或 mm-dd-yyyy
            r'(\d{1,2})[/-](\d{1,2})[/-](\d{4})'
        ]
        
        for pattern in patterns:
            match = re.match(pattern, date_str)
            if match:
                groups = match.groups()
                if len(groups) == 3:
                    try:
                        if len(groups[0]) == 4:  # yyyy/mm/dd 格式
                            year, month, day = groups
                        else:  # mm/dd/yyyy 格式
                            month, day, year = groups
                        
                        date_obj = datetime(int(year), int(month), int(day))
                        return date_obj.strftime("%Y-%m-%d")
                    except:
                        continue
        
        # 如果无法解析，返回原始字符串
        return date_str
    
    def fix_excel_id_card(self, value):
        """修复Excel中身份证号被转换为科学计数法的问题"""
        if value is None:
            return ""
            
        value = str(value).strip().upper()
        
        # 处理科学计数法：1.10101e+17 转换为 110101000000000000
        if 'e+' in value.lower():
            try:
                # 转换为浮点数再转换为整数
                num_value = float(value)
                # 格式化为18位字符串，不足的补0
                fixed_value = f"{int(num_value):018d}"
                return fixed_value
            except:
                pass
        
        # 处理数字格式的身份证号
        if value.isdigit():
            # 如果是纯数字，格式化为18位
            if len(value) <= 18:
                fixed_value = value.zfill(18)
                return fixed_value
        
        # 处理包含X的情况
        if 'X' in value:
            # 移除所有非数字和X的字符
            cleaned = re.sub(r'[^\dX]', '', value)
            if len(cleaned) == 18:
                return cleaned
        
        return value
    
    def import_excel(self):
        """导入Excel"""
        try:
            file_path, _ = QFileDialog.getOpenFileName(
                self, "选择Excel文件", "", "Excel文件 (*.xlsx *.xls)"
            )
            if file_path:
                workbook = openpyxl.load_workbook(file_path)
                sheet = workbook.active
                
                success_count = 0
                error_count = 0
                error_messages = []
                
                for row_idx, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
                    try:
                        if row and row[0] is not None:
                            # 根据Excel表头顺序映射到正确的字段
                            employee_data = (
                                str(row[1]).strip() if len(row) > 1 and row[1] is not None else "",  # 姓名
                                str(row[2]).strip() if len(row) > 2 and row[2] is not None else "",  # 性别
                                self.fix_excel_id_card(row[3]) if len(row) > 3 and row[3] is not None else "",  # 身份证号
                                self.parse_date_string(row[4]) if len(row) > 4 and row[4] is not None else "",  # 出生日期
                                str(row[5]).strip() if len(row) > 5 and row[5] is not None else "汉族",  # 民族
                                str(row[6]).strip() if len(row) > 6 and row[6] is not None else "群众",  # 政治面貌
                                str(row[7]).strip() if len(row) > 7 and row[7] is not None else "",  # 联系方式
                                str(row[8]).strip() if len(row) > 8 and row[8] is not None else "",  # 学校
                                str(row[9]).strip() if len(row) > 9 and row[9] is not None else "",  # 部门
                                str(row[10]).strip() if len(row) > 10 and row[10] is not None else "",  # 岗位
                                str(row[11]).strip() if len(row) > 11 and row[11] is not None else "",  # 职称
                                self.parse_date_string(row[12]) if len(row) > 12 and row[12] is not None else ""  # 入职日期
                            )
                            
                            # 验证必填字段
                            if not employee_data[0]:
                                raise ValueError("姓名不能为空")
                                # 验证身份证号
                            id_card = employee_data[2]
                            if not id_card:
                                raise ValueError("身份证号不能为空")
                                
                            pattern = r'^\d{17}[\dX]$'
                            if not re.match(pattern, id_card) or len(id_card) != 18:
                                raise ValueError(f"身份证号格式错误: {id_card}")
                            
                            if not employee_data[6]:
                                raise ValueError("联系方式不能为空")
                            
                            if self.db.add_employee(employee_data):
                                success_count += 1
                            else:
                                error_count += 1
                                error_messages.append(f"第{row_idx}行: 身份证号已存在或数据格式错误")
                                
                    except Exception as e:
                        error_count += 1
                        error_messages.append(f"第{row_idx}行: {str(e)}")
                
                message = f"导入完成！\n成功: {success_count} 条\n失败: {error_count} 条"
                if error_messages:
                    message += f"\n\n错误详情:\n" + "\n".join(error_messages[:5])
                    if len(error_messages) > 5:
                        message += f"\n...还有{len(error_messages) - 5}个错误"
                
                QMessageBox.information(self, "导入结果", message)
                self.load_data()
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导入失败：{str(e)}")
    
    def export_excel(self):
        """导出Excel"""
        try:
            # 先获取数据
            employees = self.db.get_all_employees()
            
            if not employees:
                QMessageBox.warning(self, "警告", "没有员工数据可导出！")
                return
            
            file_path, _ = QFileDialog.getSaveFileName(
                self, "保存Excel文件", "员工数据.xlsx", "Excel文件 (*.xlsx)"
            )
            
            if not file_path:  # 用户取消了操作
                return
            
            workbook = openpyxl.Workbook()
            sheet = workbook.active
            sheet.title = "员工数据"
            
            # 设置表头（与图片一致）
            headers = ["序号", "姓名", "性别", "身份证号", "出生日期", "民族", 
                    "政治面貌", "联系方式", "学校", "部门", "岗位", "职称", "入职日期"]
            sheet.append(headers)
            
            # 填充数据 - 从第二行开始
            for idx, emp in enumerate(employees, 2):  # 从第2行开始
                try:
                    row_data = [
                        idx - 1,  # 序号（从1开始）
                        str(emp[1]) if emp[1] is not None else "",  # 姓名
                        str(emp[2]) if emp[2] is not None else "",  # 性别
                        str(emp[3]) if emp[3] is not None else "",  # 身份证号
                        str(emp[4]) if emp[4] is not None else "",  # 出生日期
                        str(emp[5]) if emp[5] is not None else "",  # 民族
                        str(emp[6]) if emp[6] is not None else "",  # 政治面貌
                        str(emp[7]) if emp[7] is not None else "",  # 联系方式
                        str(emp[8]) if emp[8] is not None else "",  # 学校
                        str(emp[9]) if emp[9] is not None else "",  # 部门
                        str(emp[10]) if emp[10] is not None else "",  # 岗位
                        str(emp[11]) if emp[11] is not None else "",  # 职称
                        str(emp[12]) if emp[12] is not None else ""   # 入职日期
                    ]
                    
                    sheet.append(row_data)
                    
                    # 设置身份证号列为文本格式（在添加数据后设置）
                    sheet[f'D{idx}'].number_format = '@'  # D列为身份证号
                    
                except Exception as e:
                    # print(f"处理第{idx-1}条记录时出错: {e}")
                    continue
            
            # 保存文件
            workbook.save(file_path)
            
            # 验证导出结果
            if os.path.exists(file_path):
                QMessageBox.information(self, "成功", 
                                    f"成功导出 {len(employees)} 条员工数据到:\n{file_path}")
            else:
                QMessageBox.critical(self, "错误", "文件创建失败！")
                
        except Exception as e:
            error_msg = f"导出失败：{str(e)}\n\n详细错误信息:\n{traceback.format_exc()}"
            # print(error_msg)
            QMessageBox.critical(self, "错误", f"导出过程失败：{str(e)}")